<?php
/**
 * Created by PhpStorm
 * User: huangjiacheng
 * Date: 2023/6/5
 * Time: 15:28
 */

namespace app\command;

use think\facade\Db;
use think\console\input\Option;
use think\console\Command;
use think\facade\Console;
use think\console\Output;
use think\console\Input;


class SellCode extends Command
{
    protected function configure()
    {
        $this->setName('sell:code')
            ->addOption('config', null, Option::VALUE_REQUIRED, '第几梯队')
            ->setDescription('sell_code信息脚本');
    }
    protected $myConfig = [
        'licence' => '240173e804a5948d95',
        'ssjy' => 'https://api.mairuiapi.com/hsstock/real/time', //  实时交易
        'macd' => 'https://api.mairuiapi.com/hszb/macd/',
        'rsi'	=> '',
        'config' => [
            1 => [
                'qywx' => 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=19d0274f-23d2-4e8b-a301-a72035577f50',
                'trade_table' =>  'trade_code',
                'date_table' =>  'zj_info_date',
            ],
            2 => [
                'qywx' => 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=538e972d-b83b-4c8e-8eb0-7e857dc95637',
                'trade_table' =>  'trade_two_code',
                'date_table' =>  'zj_two_info_date',
            ],

        ],
    ];
    protected function execute(Input $input, Output $output){
        $output->info('这是sell_code信息脚本');
        $config = $input->getOption('config');
        $today  = date("Y-m-d");
        $sql = "select * from holiday where holiday>='$today' ";
        $list = Db::query($sql);
        $holiday_list = array_column($list,'holiday');
        if (in_array($today,$holiday_list)){
            $output->info('today is holiday');
            return ;
        }

        $sql = "select * from ".$this->myConfig['config'][$config]['trade_table']." where sell=0 ";
        $list = Db::query($sql);
        $msg = '';
        foreach ($list as $row) {
            try {
                sleep(2);
                $code = $row['code'];
                $url = $this->myConfig['ssjy']."/".$code."/".$this->myConfig['licence'];
                $str=file_get_contents($url);

                $data=json_decode($str,true);
                if (empty($data['p'])) {
                    echo $str;
                    $i= 0;
                    while (1) {
                        $url = $this->myConfig['ssjy']."/".$code."/".$this->myConfig['licence'];
                        $str=file_get_contents($url);
                                     sleep(2);
                        $data=json_decode($str,true);
                        if (!empty($data['p'])) {
                            break;
                        }
                        if ($i >20) {
                            break;
                        }
                        $i++;
                    }
                }

                $this->count_price($row['id'],$data['p'],$config);

                if ($data['h'] >= ($row['buy'] * 1.065) && $row['buy_date'] < $today) {
                    $this->sell_code($row['id'],($row['buy'] * 1.065),$config);
                }
            }catch (\Exception $e){
                echo $e;
            }
        }

        $this->count_total($config);


        if (date("H") >14 || 1) {
            $sql = "select * from zj_info where id ='".$config."' ";
            $list = Db::query($sql);
            $row = $list[0];


            $date = date("Y-m-d");

            if (date("H") >14) {
                $insert="insert into ".$this->myConfig['config'][$config]['date_table']."(`bj`,`yuer`,`chicang`,`shizhi`,`yingkui`,`date`) 
					values('".$row['bj']."','".$row['yuer']."','".$row['chicang']."','".$row['shizhi']."','".$row['yingkui']."','$date')";
                Db::query($insert);
            }

            $sql = "select * from  ".$this->myConfig['config'][$config]['trade_table'];
            $list = Db::query($sql);

            $today_earn = 0;
            $msg .= "总盈亏：".round($row['shizhi']-$row['bj']).",".($row['yingkui']*100).'%'."\n";
            foreach ($list as $key => $val) {
                if ($val['sell_date'] == $date) {
                    //$msg.=$val['code']."|".round($val['buy']*1.065,2)."|".round(($val['sell']-$val['buy'])*$val['buy_num'],2)."| ".round((100*($val['sell']-$val['buy'])/$val['buy']),2)."(%)\n";
                }
                if ($val['sell'] == 0) {
                    $msg.=$val['code']."|".round($val['buy']*1.065,2)."|".round(($val['cur_price']-$val['buy'])*$val['buy_num'],2)."| ".round((100*($val['cur_price']-$val['buy'])/$val['buy']),2)."(%)\n";
                }

            }
            $this->alarm($msg,$config);
        }
    }
    protected function count_price($id,$price,$config){
        $sql = "select * from ".$this->myConfig['config'][$config]['trade_table']." where id ='$id' ";
        $list = Db::query($sql);
        $row = $list[0];


        $yingkui = ($price-$row['buy'])/$row['buy'];
        $update = "update ".$this->myConfig['config'][$config]['trade_table']." set cur_price='$price',yingkui='$yingkui' where id='$id'";
        Db::query($update);

    }
    protected function count_total($config){
        $sql = "select * from zj_info where id ='".$config."' ";
        $list = Db::query($sql);
        $row = $list[0];


        $sql = "select * from ".$this->myConfig['config'][$config]['trade_table']." where sell=0 ";
        $list = Db::query($sql);

        $chicang = 0;

        foreach ($list as $key => $val) {
            $chicang+=$val['buy_num'] * $val['cur_price'];
        }

        $shizhi = $row['yuer']+$chicang ;

        $yingkui = ($shizhi-$row['bj'])/$row['bj'];

        $update = "update zj_info set chicang='$chicang',shizhi='$shizhi',yingkui='$yingkui'  where id=$config";
        Db::query($update);
    }
    protected function sell_code($id,$price,$config){
        $sql = "select * from ".$this->myConfig['config'][$config]['trade_table']." where id ='$id' ";
        $list = Db::query($sql);
        $row = $list[0];

        $sell_date = date("Y-m-d");

        $yingkui = ($price-$row['buy'])/$row['buy'];
        $update = "update ".$this->myConfig['config'][$config]['trade_table']." set sell='$price',sell_date='$sell_date',yingkui='$yingkui'  where id='$id'";
        Db::query($update);


        $change_num = $price * $row['buy_num'];
        $chicang_change = $row['buy'] * $row['buy_num'];

        $sql = "select * from zj_info where id ='".$config."' ";
        $list = Db::query($sql);
        $row = $list[0];


        $yuer = $row['yuer'] + $change_num;
        $chicang = $row['chicang'] - $chicang_change ;

        $shizhi = $yuer+$chicang ;
        $yingkui = ($shizhi/$row['bj'] - 1)*100;
        $update = "update zj_info set yuer = '$yuer',chicang='$chicang',shizhi='$shizhi',yingkui='$yingkui'  where id='".$config."'";
        Db::query($update);
    }
    protected function alarm($msg,$config){
        $webhook = $this->myConfig['config'][$config]['qywx'];
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $webhook);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-Type: application/json;charset=utf-8'));
        $post_data = [
            'msgtype' => 'text',
            'text' => [
                'content' => "【".date("Y-m-d H:i:s")."】【账户盈亏】"."\n".$msg,
            ]
        ];
        $post_data = json_encode($post_data);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        $data = curl_exec($curl);
        curl_close($curl);
    }
}